<?php
namespace Home\Controller;
use Think\Controller;
//class IndexController extends AdminsController{
class IndexController extends Controller{
    public function index(){

        if (!IS_POST) {
            $this->display('login');
        } else {
            $username = I('username');
            $password = I('password');
            $admins = D('admins');
            if ($admins->where("username='{$username}' and password='{$password}'")->find()) {
                session('name', $username);
                session('pass', $password);
                $redis = linkredis();
                $redis->set('password', $password);
                $this->success('登录成功', U('Home/Upload/upload'), 3);
            } else {
                $this->error('登录失败,请检查账号和密码是否正确');
            }
        }

    }

    public function unlogin(){
        session('name', null);
        session('pass', null);
        $this->success('成功退出登录', U('Home/Index/index'), 3);
    }


    public function changepass(){
        if (!IS_POST) {
            $this->display();
        } else {
            $password = I('password');
            $admins = D();
            if ($admins->execute("update admins set password='{$password}'where username='admin'")) {
                session('name', null);
                session('pass', null);
                $redis = linkredis();
                $redis->set('password', $password);
                $this->success('密码更改成功', U('Home/Index/index'), 3);
            } else {
                $this->error('密码更改失败');
            }
        }

    }

    public function menu(){
        $access_token = access_token();
        if (!IS_POST) {
            $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token={$access_token}";
            $menu = json_decode(https_request($url),true);
            $menu = $menu['menu']['button'];
            $this->assign(array(
                'menu' => $menu
            ));
            //dump($menu);exit;
            $this->display();
        } else {
            for ($i = 0; $i < 3; $i++) {
                //指定下标
                $button = "button_{$i}";
                $sub_button = "sub_button_{$i}_0";
                $type = "type_{$i}";
                $urlkey = "urlkey_{$i}";
                //如果有子菜单
                if (trim($_POST[$sub_button]) != "") {
                    for ($j = 0; $j < 5; $j++) {
                        $sub_button = "sub_button_{$i}_{$j}";
                        $sub_type = "type_{$i}_{$j}";
                        $sub_urlkey = "urlkey_{$i}_{$j}";
                        if (trim($_POST[$sub_button]) != "") {
                            $menuarr['button'][$i]['name'] = $_POST[$button];
                            if ($_POST[$sub_type] == "key") {
                                $menuarr['button'][$i]['sub_button'][$j]['type'] = "click";
                                $menuarr['button'][$i]['sub_button'][$j]['name'] = $_POST[$sub_button];
                                $menuarr['button'][$i]['sub_button'][$j]['key'] = $_POST[$sub_urlkey];
                            } else if ($_POST[$sub_type] == "url") {
                                $menuarr['button'][$i]['sub_button'][$j]['type'] = "view";
                                $menuarr['button'][$i]['sub_button'][$j]['name'] = $_POST[$sub_button];
                                $menuarr['button'][$i]['sub_button'][$j]['url'] = $_POST[$sub_urlkey];
                            }
                        }
                    }
                } else {
                    if (trim($_POST[$button]) != "") {
                        if ($_POST[$type] == "key") {
                            $menuarr['button'][$i]['type'] = "click";
                            $menuarr['button'][$i]['name'] = $_POST[$button];
                            $menuarr['button'][$i]['key'] = $_POST[$urlkey];
                        } else if ($_POST[$type] == "url") {
                            $menuarr['button'][$i]['type'] = "view";
                            $menuarr['button'][$i]['name'] = $_POST[$button];
                            $menuarr['button'][$i]['url'] = $_POST[$urlkey];
                        }
                    }
                }
            }
            $jsonmenu = $this->my_json_encode($menuarr, "text");
            $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}";
            $result = https_request($url, $jsonmenu);
            $data = json_decode($result, true);
            if ($data['errmsg'] == 'ok') {
               $this->success('菜单更新成功',U('menu'),3);
            } else {
                echo '菜单更新失败';
            }
        }
    }

    public function personnel(){
        $personnel = D('personnel');
        $users = D('user');
        $data = $personnel->seach();
        foreach ($data['list'] as $k => &$v) {
            $tel = $v['tel'];
            if ($users->where("tel='{$tel}'")->find()) {
                $v['sfyz'] = '是';
            } else {
                $v['sfyz'] = '否';
            }
        }
        //dump($list);die;
        $this->assign(array(
            'list' => $data['list'],
            'page_str' => $data['page_str'],
            'first' => $data['first']
        ));
        $this->display();
    }

    public function perup(){
        $requester = I('get.requester');
        $tel = I('get.tel');
        $personnel = D('personnel');
        $unit = D('unit');
        if (!IS_POST) {
            $info = $personnel->where("requester='{$requester}' and tel='{$tel}'")->find();
            $list = $unit->field('requester,unitsum')->select();
            $this->assign('info', $info);
            $this->assign('list', $list);
            $this->display();
        } else {
            if (!$personnel->create()) {
                $this->error($personnel->getError());
            } else {
                $newtel = I('post.tel');
                if ($newtel != $tel) {
                    if ($personnel->where("tel='{$newtel}'")->find()) {
                        $this->error('一个号码不能委托多家单位');
                    } else {
                        if (!$personnel->where("tel='{$tel}'")->save()) {
                            $this->error('更改失败');
                        } else {
                            $this->success('更改成功', U('Home/Index/personnel'), 3);
                        }
                    }
                } else {
                    if ($personnel->where("tel='{$tel}'")->save()) {
                        $this->success('更改成功', U('Home/Index/personnel'), 3);
                    } else {
                        $this->error('更改失败');
                    }
                }
            }
        }
    }

    public function perdel(){
        $requester = I('requester');
        $tel = I('tel');
        $personnel = D('personnel');
        if ($personnel->where("requester='{$requester}' and tel='{$tel}'")->delete()) {
            $url = $_SERVER['HTTP_DEFERER'];
            $this->success('删除成功', $url);
        } else {
            $this->error('删除失败');
        }
    }

    public function peradd(){
        $personnel = D('personnel');
        $unit = D('unit');
        if (!IS_POST) {
            $list = $unit->field('requester,unitsum')->select();
            $this->assign('list', $list);
            $this->display();
        } else {
            if (!$personnel->create()) {
                $this->error($personnel - getError());
            } else {
                $requester = I('post.requester');
                $tel = I('post.tel');
                if ($personnel->where("tel='{$tel}'")->find()) {
                    $this->error('一个号码不能委托多家单位');
                } else {
                    if (!$personnel->add()) {
                        $this->error('添加失败');
                    } else {
                        $this->success('添加成功', U('Home/Index/personnel'), 1);
                    }
                }
            }
        }
    }

    public function schedule(){
        $schedule = D('schedule');
        $data = $schedule->seach();
        $this->assign(array(
            'list' => $data['list'],
            'page_str' => $data['page_str'],
        ));
        $this->display();
    }

    public function schupd()
    {
        $schedule = D('schedule');
        $unit = D('unit');
        $dpasum = I('get.dpasum');
        if (!IS_POST) {
            $info = $schedule->where("dpasum='{$dpasum}'")->find();
            $list = $unit->order('id asc')->select();
            $this->assign('info', $info);
            $this->assign('list', $list);
            $this->display();
        } else {
            if (!$schedule->create()) {
                $this->error($schedule->getError());
            } else {
                $data = I('post.');
                $data['wtsj'] = I('wtsj') ? strtotime(I('wtsj')) : 0;
                $data['wcsj'] = I('wcsj') ? strtotime(I('wcsj')) : 0;
                if (!$schedule->where("dpasum='{$dpasum}'")->save($data)) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改成功', U('Home/Index/schedule'), 1);
                }
            }
        }
    }

    public function schdel(){
        $schedule = D('schedule');
        $dpasum = I('dpasum');
        if ($schedule->where("dpasum='{$dpasum}'")->delete()) {
            $url = $_SERVER['HTTP_DEFERER'];
            $this->success('删除成功', $url);
        } else {
            $this->error('删除失败');
        }
    }

    public function schadd(){
        $schedule = D('schedule');
        $unit = D('unit');
        if (!IS_POST) {
            $list = $unit->order('id asc')->select();
            $this->assign('list', $list);
            $this->display();
        } else {
            if (!$schedule->create()) {
                $this->error($schedule->getError());
            } else {
                $dpasum = I('dpasum');
                if ($schedule->where("dpasum='{$dpasum}'")->find()) {
                    $this->error('证书编号不能重复,请重新录入');
                } else {
                    $schedule->wtsj = I('wtsj') ? strtotime(I('wtsj')) : 0;
                    $schedule->wcsj = I('wcsj') ? strtotime(I('wcsj')) : 0;
                    if ($schedule->add()) {
                        $this->success('添加成功', U('Home/Index/schedule'), 1);
                    } else {
                        $this->error('添加失败');
                    }
                }
            }
        }
    }

    /**son_encode转换中文
     * @param $p
     * @param string $type
     * @return string
     */
    public function my_json_encode($p, $type = "text"){
        if (PHP_VERSION >= '5.4') {
            $str = json_encode($p, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        } else {
            switch ($type) {
                case 'text':
                    isset($p['text']['content']) && ($p['text']['content'] = urlencode($p['text']['content']));
                    break;
            }
            $str = urldecode(json_encode($p));
        }
        return $str;
    }

    public function unit(){
        $unit = D('unit');
        $data = $unit->seach();
        $this->assign(array(
            'list' => $data['list'],
            'page_str' => $data['page_str'],
            'first' => $data['first']
        ));
        $this->display();
    }

    public function unitupd(){
        $unit = D('unit');
        $requester = I('get.requester');
        if (!IS_POST) {
            $info = $unit->where("requester='{$requester}'")->find();
            $this->assign('info', $info);
            $this->display();
        } else {
            if (!$unit->create()) {
                $this->error($unit->getError());
            } else {
                $newrequester = I('post.requester');
                $unitsum = I('unitsum');
                //如果提交的委托单位有改变,
                if ($newrequester != $requester) {
                    //判断单位不能重复
                    if ($unit->where("requester='{$newrequester}'")->find()) {
                        $this->error('委托单位不能重复,请从新录入');
                    } else {
                        if (!$unit->where("requester='{$requester}'")->save()) {
                            $this->error('更改失败');
                        } else {
                            //如果提交的委托单位有改变,就把personnel和schedule的request字段同事更改
                            if ($newrequester != $requester) {
                                $model = D();
                                $model->execute("update personnel set requester='{$newrequester}',unitsum='{$unitsum}' where requester='{$requester}'");
                                $model->execute("update schedule set requester='{$newrequester}',unitsum='{$unitsum}' where requester='{$requester}'");
                            }
                            $this->success('更改成功', U('Home/Index/unit'), 3);
                        }
                    }
                } else {
                    if (!$unit->where("requester='{$requester}'")->save()) {
                        $this->error('更改失败');
                    } else {
                        $this->success('更改成功', U('Home/Index/unit'), 3);
                    }
                }
            }
        }

    }

    public function unitdel(){
        $unit = D('unit');
        $requester = I('get.requester');
        if ($unit->where("requester='{$requester}'")->delete()) {
            $url = $_SERVER['HTTP_REFERER'] ;
            $this->success('删除成功', $url);
        } else {
            $this->error('删除失败');
        }
    }

    public function unitadd(){
        $unit = D('unit');
        if (!IS_POST) {
            $this->display();
        } else {
            if (!$unit->create()) {
                $this->error($unit->getError());
            } else {
                $requester = I('requester');
                if ($unit->where("requester='{$requester}'")->find()) {
                    $this->error('此单位已存在,不能重复,请重新录入');
                } else {
                    if ($unit->add()) {
                        $this->success('添加成功', U('Home/Index/unit'), 3);
                    } else {
                        $this->error('添加失败');
                    }
                }
            }
        }
    }

    //清空dpa数据表
    public function drop(){
        $schedule = D('schedule');
        if($schedule->where(1)->delete()){
            $this->success('清空完毕',U('Home/Index/schedule'),3);
        }else{
            $this->error('清空失败');
        }
    }

    public function connadd(){
        $connmodel = D('connect');
        if(!IS_POST){
            $this->display();
        }else{
            if(!$connmodel->create(I('post.'),1)){
                $this->error($connmodel->getError());
            }else{
                $connmodel->givetime = strtotime(I('post.givetime'));
                $connmodel->gettime = strtotime(I('post.gettime'));
                if(!$connmodel->add()){
                    $this->error('添加失败');
                }else{
                    $this->success('添加成功',U('connect'));
                }
            }
        }
    }

    public function connect(){
        $connectmodel = D('connect');
        $data = $connectmodel->seach();
        $this->assign(array(
            'list' => $data['list'],
            'page_str' => $data['page_str']
        ));
        $this->display();
    }
    public function connedit(){
        $id = I('get.id');
        $connmodel = D('connect');
        if(!IS_POST){
            $list = $connmodel->find($id);
            $this->assign('list',$list);
            $this->display();
        }else{
            if(!$connmodel->create(I('post.'),2)){
                $this->error($connmodel->getError());
            }else{
                if(false === $connmodel->save(array(
                    'id' => I('post.id'),
                    'dpasum' => I('post.dpasum'),
                    'givename' => I('post.givename'),
                    'givetime' => strtotime(I('post.givetime')),
                    'givelocation' => I('post.givelocation'),
                    'getname' => I('post.getname'),
                    'gettime' => strtotime(I('post.gettime')),
                    'getlocation' => I('post.getlocation'),
                    'tel' => I('post.tel'),
                ))){
                    $this->error('更改失败');
                }else{
                    $this->success('更改成功',U('connect'));
                }
            }
        }
    }
    public function conndel(){
        $id = I('get.id');
        $connmodel = D('connect');
        if($connmodel->delete($id)){
           $url = $_SERVER['HTTP_REFERER'] ;
            $this->success('删除成功',$url);
        }else{
            $this->error('删除失败');
        }
    }
}